package com.colorfruit.admin.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.colorfruit.admin.business.dao.FoundationSysUserMapper;
import com.colorfruit.admin.business.service.LoginService;
import com.colorfruit.admin.outer.weixin.WxUtil;
import com.colorfruit.admin.pojo.entity.FoundationSysUser;
import com.colorfruit.admin.pojo.enums.AdminRedisEnum;
import com.colorfruit.admin.pojo.enums.ErrorCodeEnum;
import com.colorfruit.admin.pojo.enums.StatusEnum;
import com.colorfruit.admin.pojo.model.SysUserModel;
import com.colorfruit.admin.pojo.model.WxLoginRes;
import com.colorfruit.framework.common.idgenerate.BizNumberType;
import com.colorfruit.framework.common.idgenerate.DateTimeIdGenerator;
import com.colorfruit.framework.model.pojo.BaseResult;
import com.colorfruit.framework.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;


@Slf4j
@Service
@Transactional
public class LoginServiceImpl implements LoginService {

    @Autowired
    FoundationSysUserMapper sysUserMapper;

    @Autowired
    RedisCache redisCache;

    @Value("${app_id}")
    String appId;

    @Override
    public BaseResult wxLogin(String code,
                              String nickName,
                              String userImgUrl,
                              Byte userSex) {
        try {
            log.info("[service] [IN] wuLogin param : code = {}, nickName = {}, userImgUrl = {}, userSex = {}",
                    code, nickName, userImgUrl, userSex);
            String wxResponse = WxUtil.wxLogin(code, appId);
            WxLoginRes wxLoginRes = JSON.parseObject(wxResponse, new TypeReference<WxLoginRes>() {});
            FoundationSysUser sysUser = sysUserMapper.getUserByOpenId(wxLoginRes.getOpenid());
            //1. 新用户生成用户记录
            if (sysUser == null){
                sysUser = new FoundationSysUser();
                String idNo = DateTimeIdGenerator.nextNo(BizNumberType.ID);
                sysUser.setId(idNo);
                sysUser.setRecordStatus(StatusEnum.EFFECTIVE_STATUS.getStatusCode());
                sysUser.setWxId(wxLoginRes.getOpenid());
                sysUser.setWxNick(nickName);
                sysUser.setUserName(nickName);
                sysUser.setWxHeadImgUrl(userImgUrl);
                sysUser.setSex(userSex);
                sysUser.setRoleId((long)1);
                sysUser.setWalletBalance(new BigDecimal(0));
                sysUserMapper.insert(sysUser);
            }
            //2. 生成redis tocken
            String token = DateTimeIdGenerator.nextNo(BizNumberType.TOCKEN);;
            SysUserModel sysUserModel = new SysUserModel();
            sysUserModel.setId(sysUser.getId());
            sysUserModel.setNickName(nickName);
            sysUserModel.setUserName(sysUser.getUserName());
            sysUserModel.setUserSex(userSex);
            sysUserModel.setToken(token);
            sysUserModel.setUserImgUrl(userImgUrl);
            sysUserModel.setRoleId(sysUser.getRoleId());
            redisCache.putCacheWithExpireTime(AdminRedisEnum.SYS_USER_PREFIX.getKey() + token, JSONObject.toJSONString(sysUserModel), 3600 * 4);   // 过期时间改为4小时
            log.info("[service] [OUT] wuLogin success ");
            return new BaseResult(sysUserModel);
        }catch (Exception e){
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public BaseResult testRedis() {
        try {
            redisCache.putCache("asdf","asdsdf");
            return new BaseResult(ErrorCodeEnum.SUCCESS);
        }catch (Exception e){
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }
}
